import 'package:flutter/material.dart';
import 'package:wayofdressing/all_information/user_information.dart';
import 'package:wayofdressing/all_widget/head_image.dart';
import 'package:wayofdressing/contraints.dart';
import 'package:wayofdressing/components/inmenubutton.dart';
import 'package:wayofdressing/components/message.dart';
import 'package:wayofdressing/components/bottommenu.dart';
import 'package:wayofdressing/vivo_connect.dart';

class AiChatScreen extends StatefulWidget {
  static final String id = 'aichatscreen';

  @override
  State<AiChatScreen> createState() => _AiChatScreenState();
}

class _AiChatScreenState extends State<AiChatScreen> {
  List<Widget> Messages = [];
  Widget bottomMenu = const SizedBox();

  TextEditingController textControll = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  FocusNode _contentFocusNode = FocusNode();

  Widget trailingIcon = Container();
  bool isOpen = false;

  @override
  void initState() {
    super.initState();
    Messages.add(Message(id:0,name:'peanut',text: '...', isOpposite: true,sentAt: DateTime.now(),oppositeHeadImage: AssetImage('images/peanut.jpg'),));
    _getAnswer('你的身份是穿搭导师Peanut，作为穿搭导师向我问好');
    trailingIcon = menuButton();
    _contentFocusNode.addListener(() {
      if (_contentFocusNode.hasFocus) {
        setState(() {
          bottomMenu = const SizedBox();
          isOpen = false;
        });
      }
    });
  }

  @override
  void dispose() {
    textControll.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffffaf0),
      appBar: AppBar(
        backgroundColor: Color(0xfffffaf0),
        elevation: 0,
        toolbarHeight: 80,
        leadingWidth: 100,
        centerTitle: true,
        title: const Text(
          'Peanut',
          style: TextStyle(
            color: Colors.black,
            fontWeight: FontWeight.bold,
            fontSize: kTopTitleFontSize,
          ),
        ),
        leading: Row(
          children: [
            const SizedBox(
              width: 10,
            ),
            GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Transform.scale(
                scaleX: -1,
                child: Icon(
                  Icons.play_arrow_rounded,
                  size: kAppBarButtonSize,
                  color: Colors.black.withOpacity(0.5),
                ),
              ),
            ),
          ],
        ),
        actions: [
          MenuAnchor(
            menuChildren: [
              InMenuButton(
                onPressed: () {
                  setState(() {
                    Messages = [];
                    _getAnswer('你的身份是穿搭导师Peaunt，作为穿搭导师向我问好');
                  });
                },
                text: '清空内容',
                alignment: Alignment.centerRight,
              ),
              InMenuButton(
                onPressed: () {},
                text: '自定义Peaunt',
                alignment: Alignment.centerRight,
              ),
              InMenuButton(
                onPressed: () {},
                text: '设置',
                alignment: Alignment.centerRight,
              ),
            ],
            style: MenuStyle(
              shape: MaterialStateProperty.all(
                RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0),
                ),
              ),
              alignment: const Alignment(-3, 0.5),
              padding: MaterialStateProperty.all(const EdgeInsets.all(15.0)),
              shadowColor: MaterialStateProperty.all(Colors.transparent),
              backgroundColor: MaterialStateProperty.all(
                Colors.black.withOpacity(0.4),
              ),
            ),
            builder: (BuildContext context, MenuController controller,
                Widget? child) {
              return GestureDetector(
                onTap: () {
                  if (controller.isOpen) {
                    controller.close();
                  } else {
                    controller.open();
                  }
                },
                child: const Icon(
                  Icons.keyboard_control_rounded,
                  size: kAppBarButtonSize,
                  color: Colors.black,
                ),
              );
            },
          ),
          const SizedBox(
            width: 20,
          )
        ],
      ),
      body: GestureDetector(
        onTap: () {
          if (_contentFocusNode.hasFocus) {
            setState(() {
              _contentFocusNode.unfocus();
            });
          }
        },
        child: Column(
          children: [
            Expanded(
              flex: 4,
              child: ListView.builder(
                controller: _scrollController,
                itemCount: Messages.length,
                itemBuilder: (context, index) {
                  return Messages[index];
                },
              ),
            ),
            Container(
              width: MediaQuery.of(context).size.width,
              height: 70,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    width: 42,
                    height: 42,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(25),
                        border: Border.all(color: Colors.black, width: 4)),
                    child: Icon(
                      Icons.mic_none_rounded,
                      color: Colors.black,
                      size: 35,
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.symmetric(vertical: 12, horizontal: 10),
                    width: MediaQuery.of(context).size.width - 150,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(25.0),
                      color: Colors.black.withOpacity(0.3),
                    ),
                    child: TextField(
                      focusNode: _contentFocusNode,
                      controller: textControll,
                      cursorColor: Colors.white,
                      onChanged: (value) {
                        setState(() {
                          if (textControll.text != '') {
                            trailingIcon = sendButton();
                          } else {
                            trailingIcon = menuButton();
                          }
                        });
                      },
                      style: const TextStyle(
                        color: Colors.black,
                        fontSize: 18,
                      ),
                      decoration: InputDecoration(
                        contentPadding:
                            EdgeInsets.symmetric(horizontal: 15, vertical: 13),
                        border: InputBorder.none,
                      ),
                    ),
                  ),
                  trailingIcon,
                ],
              ),
            ),
            bottomMenu,
          ],
        ),
      ),
    );
  }

  Future<void> _getAnswer(String prompt) async {
    final result = await vivogpt(prompt);
    setState(() {
      Messages.last=(Message(id:0,name:'peanut',text: result, isOpposite: true,sentAt: DateTime.now(),oppositeHeadImage: AssetImage('images/peanut.jpg'),));
    });
    Future.delayed(const Duration(milliseconds: 200), () {
      _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
    });
  }

  GestureDetector menuButton() {
    return GestureDetector(
      onTap: () {
        setState(() {
          _contentFocusNode.unfocus();
          if (!isOpen) {
            bottomMenu = BottomMenu(context: context);
            isOpen = true;
          } else {
            bottomMenu = const SizedBox();
            isOpen = false;
          }
        });
      },
      child: const Icon(
        Icons.add_circle_outline_rounded,
        size: 50,
        color: Colors.black,
      ),
    );
  }

  GestureDetector sendButton() {
    return GestureDetector(
      onTap: () {
        setState(() {
          Messages.add(Message(id:userId,name:name,text: textControll.text, isOpposite: false,sentAt: DateTime.now(),oppositeHeadImage:headImage,));
          Messages.add(Message(id:0,name:'peanut',text: '...', isOpposite: true,sentAt: DateTime.now(),oppositeHeadImage: AssetImage('images/peanut.jpg'),));
        });
        _getAnswer(textControll.text);
        textControll.clear();
        trailingIcon = menuButton();
        Future.delayed(const Duration(milliseconds: 200), () {
          _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
        });
      },
      child: CircleAvatar(
        backgroundColor: Colors.blueAccent,
        child: const Icon(
          Icons.send_rounded,
          size: 28,
          color: Colors.white,
        ),
      ),
    );
  }
}
